﻿using DocumentFormat.OpenXml.Spreadsheet;
using DotNetCore.CAP;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using NP.Enterprise.Utils.Http;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.Utils;

namespace NP.BPMReportPlatform.RecurringJobs
{
    public class SeminarManageJob : BpmReportPlatformRecurringJob, ISeminarManageJob
    {
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly SqlSugarClient _db, _dbPlatform;
        private ICapPublisher _capBus;
        private readonly IBPMUtilsAppService _bPMUtilsApp;
        private readonly string _pcUrlTemplate;
        private readonly string _tokenTimeout;
        private readonly string _urlTemplate;

        public SeminarManageJob(INPRestHttpHelper httpClient,
            ISqlSugarAppService sqlSugarAppService,
            ICapPublisher publisher,
            IConfiguration configuration,
            IBPMUtilsAppService bPMUtilsApp)
        {
            _urlTemplate = configuration["Nippon:LCZXRZXQGL:template"];
            _pcUrlTemplate = configuration["BPM:PcUrlTemplate"];
            _tokenTimeout = configuration["BPM:TokenTimeout"];
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _capBus = publisher;
            _bPMUtilsApp = bPMUtilsApp;
        }

        /// <summary>
        /// 预计会议日期+7日后，系统查询当前状态为待申请人结案的单据，需要系统催办。
        /// </summary>
        /// <returns></returns>
        public async Task SyncSeminarManage()
        {
            TUSeminarManageLog log = new TUSeminarManageLog();
            try
            {
                var getSeminarManage = await _db.Queryable<TUSeminarManageHeader>().Where(x => x.MeetTime.Value.AddDays(7) < DateTime.Now && x.Status == 4
                &&(x.MeetType== "项目推广会"|| x.MeetType == "合作伙伴推广会" || x.MeetType == "客户推广会" || x.MeetType == "设计院推广会" || x.MeetType == "行业交流")).ToListAsync();
                if (getSeminarManage.Count > 0)
                {
                    foreach (var item in getSeminarManage)
                    {
                        log = new TUSeminarManageLog();
                        log.InstanceNumber = item.InstanceNumber;
                        var userInfo = await _dbPlatform.Queryable<Entities.BPM_Platform.Users>().Where(x => x.UserId.Equals(item.AddUserId)).FirstAsync();
                        if (userInfo != null) {
                            // var newUrl = _bPMUtilsApp.GetProcessUrl(item.InstanceNumber, userInfo.UserId.ToString()); ;
                            //var pUrl = string.Format(_pcUrlTemplate, item.InstanceNumber) + $"?token={MT.Enterprise.Utils.Crypto.JwtEncrypt($"{item.InstanceNumber}|{userInfo.UserId}", int.Parse(_tokenTimeout))}";

                            var pUrl = _urlTemplate.Replace("{str}", item.InstanceNumber);

                            await _capBus.PublishAsync("bpmnew.EmailAppService.SendEmailAsync",
                            new SendEmailSimpleDto()
                            {
                                To = userInfo.Email,
                                Subject = "一般推广会" + item.InstanceNumber + "结案催办",
                                Body = $"您好，您有一个一般推广会（单据号：" + item.InstanceNumber + "）亟需结案，否则影响整个大区其他人员进行会议申请，请尽快结案。:<a href='" + pUrl + "'>" + item.InstanceNumber + "<a/>",
                                InstanceNumber = item.InstanceNumber
                            });
                            log.Type = "Email";
                            log.Node = "预计会议抄送申请人";
                            log.Title = userInfo.Email;
                            log.Msg = $"您好，您有一个一般推广会（单据号：" + item.InstanceNumber + "）亟需结案，否则影响整个大区其他人员进行会议申请，请尽快结案。:<a href='" + pUrl + "'>" + item.InstanceNumber + "<a/>";
                            log.CreateDate = DateTime.Now;
                            await _db.Insertable(log).ExecuteCommandAsync();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Type = "Error";
                log.Node = "预计会议抄送申请人错误";
                log.Title = "";
                log.Msg = ex.Message;
                log.CreateDate = DateTime.Now;
                await _db.Insertable(log).ExecuteCommandAsync();
            }
        }
    }
}
